import { BusinessItemListInfo } from "../../types/business";
import { clone, find, findIndex, get, pick, set } from "lodash";
import { FC, InputHTMLAttributes, RefObject, useRef } from "react";
import { Button, Form, FormInstance, Input, Slider } from "antd";
import Dialog from "../Dialog";
import SourcePos from "./SourcePos";
import ImageListUpload from "./ImageListUpload";
import request from "../../utils/request";
import crop from "../../utils/cropping";

const getFormFileData = (file: any) => {
  const formData = new FormData();
  formData.append("file", file)
  return formData
}

export const iconDialog = (data?: BusinessItemListInfo) => {
  const isModify = !!data;
  //@ts-ignore
  let newData: BusinessItemListInfo = clone(data);
  const initialData = {
    name: "",
    media_info: [],
    threshold: 0.8,
    score: 1
  };
  if (isModify) {
    initialData.name = data.name;
    // @ts-ignore
    initialData.media_info = get(data, "media_info", []);
    initialData.threshold = get(data, "threshold", 0);
    initialData.score = get(data, "score", 0);
  }
  return new Promise((resolve, reject) => {
    let formRef: RefObject<FormInstance>;

    const onDelete = (item: any, idx: number) => {
      if (!formRef.current) return;
      const list = formRef.current.getFieldValue("media_info") || [];
      // const idx = findIndex(list, { url: item?.url });
      if (idx !== -1) {
        list.splice(idx, 1);
        formRef.current.setFieldValue("media_info", clone(list));
      }
    };

    const IconInnerFileNode: FC = () => {
      const fileRef = useRef<HTMLInputElement | null>(null);
      const onActiveUpload = () => {
        fileRef.current?.click();
      };
      const onFileChange: InputHTMLAttributes<any>["onChange"] = (e) => {
        const [file] = e.target.files;
        if (!file) return;
        const fileReader = new FileReader();
        fileReader.onload = () => {
          let info;
          let posStyle;
          Dialog({
            width: 600,
            title: "图标定位",
            content: <SourcePos source={fileReader.result} getInfo={(v, pos) => {
              info = v;
              posStyle = pos;
            }} />,
            onOk: async (_,hidden) => {
              if (!formRef.current) return;
              const  list = clone(formRef.current.getFieldValue("media_info") || []);
              const data = await request.post("/hyqz/uploadFile", getFormFileData(file))
              const picRes = await request.post("/hyqz/validate/pic", {
                type: 2,
                roi: info,
                url: data,
              });
              const crop_urlData = await crop(file, posStyle)
              const crop_url = await request.post("/hyqz/uploadFile", getFormFileData(crop_urlData))

              list.push({
                media_url: data,
                crop_url,
                roi: info,
                ...picRes,
              })
              formRef.current.setFieldValue("media_info", list)
              hidden();
            }
          });
        };
        e.target.value = ''
        fileReader.readAsDataURL(file);
      };
      return [
        <input
          type="file"
          className="h-0 w-0 opacity-0"
          ref={fileRef}
          onChange={onFileChange}
          multiple={false}
        />,
        <Button type="primary" size="small" onClick={onActiveUpload}>
          新增图标
        </Button>,
      ];
    };

    const onUploadChange = (source: any) => {
      let info = [...(source?.roi)];
      let posStyle;
      Dialog({
        width: 600,
        title: "图标定位",
        content: <SourcePos source={source?.media_url} roi={source?.roi} getInfo={(v, pos) => {
          info =  [
            ...v
          ]
          posStyle = pos
        }} />,
        onOk: async (_,hidden) => {
          if (!formRef.current) return;
          const  list = clone(formRef.current.getFieldValue("media_info") || []);
          const findIdx = findIndex(list, {media_url: source?.media_url});
          if (findIdx === -1) return;
          const picRes = await request.post("/hyqz/validate/pic", {
            type: 2,
            roi: info,
            url: source?.media_url,
          });
          const crop_urlData = await crop(source?.media_url, posStyle)
          const crop_url = await request.post("/hyqz/uploadFile", getFormFileData(crop_urlData))
          set(list, `[${findIdx}]`, {
            ...list?.[findIdx],
            crop_url,
            roi: info,
            ...picRes
          })
          formRef.current.setFieldValue("media_info", list)
          hidden();
        }
      })
    }

    Dialog({
      title: isModify ? "图标编辑" : "新增图标",
      width: 600,
      content: (
        <Form initialValues={initialData} getFormRef={(v) => {
          formRef = v
        }}>
          <Form.Item label="图标名称" name="name">
            <Input />
          </Form.Item>
          <Form.Item label="上传图标" name="media_info">
            <ImageListUpload
              addLabel="新增图标"
              btnNode={<IconInnerFileNode />}
              onClick={(info) => {
                onUploadChange(info)
              }}
              onDelete={onDelete}
            />
          </Form.Item>
          <Form.Item label="阈值" name="threshold">
            <Slider min={0} max={1} step={0.01} />
          </Form.Item>
          <Form.Item label="分数" name="score">
            <Slider min={0} max={10} />
          </Form.Item>
        </Form>
      ),
      onOk: (values, hidden) => {
        if (!isModify) {
          newData = {};
        }
        Object.assign(newData, pick(values, ["name", "score"]));
        newData.threshold = get(values, "threshold", 0);
        set(newData, "media_info", clone(values.media_info));

        resolve(newData);
        hidden()
      },
      onCancel: reject,
    });
  });
};
